<template>
  <div>
    <EditorVue
        :content="content"
        :readOnlys="readOnlys"
        @changeData="hChangeData"
        @uploadImg="hUploadImg"
    />
    <el-divider></el-divider>

    <!-- 文档信息编辑 -->
    <div>
      <div class="form">
        <el-form :model="ruleForm" ref="ruleForm" label-width="100px" class="demo-ruleForm" :rules="formRule">
          <!--          <el-form-item label="文档分类" prop="nClass">-->
          <!--            <el-select v-model="ruleForm.nClass" placeholder="请选择文档类别" style="float: left">-->
          <!--              <el-option label="新闻" value="新闻"></el-option>-->
          <!--              <el-option label="通告" value="通告"></el-option>-->
          <!--              <el-option label="重要信息" value="重要信息"></el-option>-->
          <!--            </el-select>-->
          <!--          </el-form-item>-->

          <!--            <el-form-item label="是否为通知" prop="notice" style="text-align:left;float:left;padding-right: 60px;margin-left: 10px">-->
          <!--                <el-checkbox label="" name="notice" v-model="ruleForm.notice"></el-checkbox>-->
          <!--            </el-form-item>-->

          <el-form-item label="文档标题" prop="title">
            <el-input v-model="ruleForm.title" style="width: 220px;float: left"></el-input>
          </el-form-item>

<!--          <el-form-item label="设为重要新闻" prop="nImportant" style="text-align: left;padding-left: 120px">-->
<!--            <el-checkbox label="" name="imortant" v-model="ruleForm.important"></el-checkbox>-->
<!--          </el-form-item>-->

          <!-- <div v-if="this.$route.query.nClass==='新闻'"> -->
          <div>
            <el-form-item label="设为首页新闻" prop="nNews" style="text-align: left;padding-left: 120px">
              <el-checkbox label="" name="news" v-model="ruleForm.isMain"></el-checkbox>
            </el-form-item>
          </div>

          <div class="img" v-if="ruleForm.isMain==1">
            <el-upload
                class="upload-demo"
                drag
                action="string"
                accept=".jpg,.png,.jpeg,.bmp,.webp"
                :multiple="false"
                :limit="1"
                :http-request="uploadFileAndParams"
                :auto-upload="false"
                :on-remove="handleRemove"
                :before-upload="beforeAvatarUpload"
                ref="upload"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em> <br> <strong>建议1000x200px大小的图片</strong></div>
              <div class="el-upload__tip" slot="tip"><strong>jpg/png/jpeg/bmp/webp</strong>，且<strong>不超过2MB</strong>
                <br/>
                为达到最好效果，请选择<strong>1000x200px</strong>的图片</div>
            </el-upload>
          </div>

          <el-form-item style="padding:0px 80px 10px 0px;">
            <el-button type="primary" @click="uploadImg()">提交</el-button>
            <el-button @click="resetForm('ruleForm')">重置</el-button>
          </el-form-item>

        </el-form>
      </div>
    </div>

  </div>
</template>

<script>
import EditorVue from '../components/editorVue.vue'
export default {
  name: "AddNews",
  components: {
    EditorVue,
    // ChooseLocalFile
  },
  //从父组件传过来的数据，为回显的数据
  props: {
    // oldRuleForm:{
    //   type:String, //数据类型有 String、Number、Boolean、Array ...
    //   default:''// 默认值
    // },
    from: {
      type: String,
      default: ''
    },
    dialogFormVisibleAdd: {
      type: Boolean,
      default: true
    }
  },
  data() {
    // this.ruleForm=JSON.parse(this.formData);
    return {
      isChecked: false,
      params: new FormData(),
      readOnlys: false,
      dialogFormVisible1: false,
      dialogFormVisible2: false,
      content: '',
      ruleForm: {},
      formRule: {
        title: [
          {required: true, message: '请输入标题名称', trigger: 'blur'},
          {min: 1, max: 200, message: '长度在 1 到 200 个字符', trigger: 'blur'}
        ],
      },
      fileList: []
    };
  },
  methods: {
    hChangeData(editDataHtml) {
      // 获取最新的html数据
      this.content = editDataHtml
    },
    hUploadImg(file, insertFn) {
      console.log(file)
      // 插入图片，调接口返回图片url,通过插入conteng
      let imgUrl = 'https://img1.baidu.com/it/u=608404415,1639465523&fm=253&fmt=auto&app=120&f=JPEG?w=1280&h=800'
      insertFn(imgUrl);
      // 设置只读
      // this.readOnlys = true;
    },
    //限定添加新闻图片的图片大小
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isLt2M;
    },
    // submitForm() {
    //   console.log("content=====================")
    //   console.log(this.content);
    //   this.$refs["ruleForm"].validate((valid) => {
    //     if (valid) {
    //       alert('submit!');
    //       this.$refs.upload.submit();
    //       this.params.append("n_id",this.ruleForm.nId)
    //       this.params.append("n_title",this.ruleForm.nTitle)
    //       this.params.append("n_content",this.content)
    //       this.params.append("n_class",this.ruleForm.nClass)
    //       this.$axios.post("/news/modifyNews/",params).then(
    //           (res) => {
    //             if(res.data.code === 200){
    //               this.$message.success("修改成功!");
    //               // this.$router.push({path:'/allMassage',query:this.ruleForm.nClass});
    //             }
    //             else{
    //               this.$message.error("修改失败")
    //             }
    //
    //           }
    //       )
    //     } else {
    //       console.log('error submit!!');
    //       return false;
    //     }
    //   });
    // },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    handleChange(event) {
      console.log(event)
      // document.getElementById("img").style.display="block";
    },
    // 文件上传
    submitUpload() {
      this.$refs.upload.submit();
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
      this.params.remove('file');
    },
    uploadFileAndParams(param) {
      this.params.append("picture", param.file)
    },
    handlePreview(file) {
      console.log(file);
    },
    Img(param) {
      this.file = param.file;
    },
    uploadImg() {
      this.$refs.ruleForm.validate((valid) => {
        if(valid){
        let config = {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        };
        if (this.ruleForm.isMain == 1) {
          this.$refs.upload.submit();
          this.params.append('isMain', 1)

        }
        else{
          this.params.append('picture',null);
          this.params.append('isMain', 0)
        }
        // let params = new FormData();
        this.params.append('title', this.ruleForm.title)
        this.params.append('authorId', localStorage.getItem('authorId'))
        this.params.append('module', this.from)
        this.params.append('content', this.content)
          //重要新闻？
          // this.params.append('n_imporant',this.ruleForm.important)
        this.$axios.post('/article/article/addArticle', this.params, config).then((res) => {
          if (res.data.code === 200) {
            this.$message.success("上传成功！")
            this.shutdown();
          } else if (res.data.code === 401) {
            this.$message.error("无权限！");
          } else {
            this.$message.error('上传失败！')
          }
        }).finally(() => {
          this.shutdown();
          this.$emit('success', false);
        })}
      });
    },
    shutdown: function () {
      this.$emit('update:shutdown', false)
    }
  },
  mounted() {

  },

};
</script>
<style scoped>
.form {
  width: 400px;
  margin: 0 auto;
  box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)
}

.img {
  padding-bottom: 10px;
}
</style>
